// src/user/user.controller.ts
import { Controller, Get, Post, Body, Patch, Param, Delete, Render, UnauthorizedException } from '@nestjs/common';
import { UserService } from './user.service';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';

@Controller('user')
export class UserController {
  constructor(private readonly userService: UserService) {}

  @Post()
  create(@Body() createUserDto: CreateUserDto) {
    return this.userService.create(createUserDto);
  }

  // 展示登录页面
  @Get('login')
  @Render('login')
  showLoginPage() {
    // 可以传递数据到模板
    return { title: '用户登录' };
  }

  // 处理登录请求
  @Post('login')
  async login(@Body() createUserDto: CreateUserDto) {
    try {
      const result = await this.userService.login(createUserDto);
      // 登录成功返回token（可以根据需求调整为JSON或跳转）
      return result;
    } catch (error) {
      // 抛出异常，让全局异常过滤器处理
      if (error instanceof UnauthorizedException) {
        throw error;
      }
      throw new UnauthorizedException('登录失败');
    }
  }
  
  @Get()
  findAll() {
    return this.userService.findAll();
  }

  @Get(':id')
  findOne(@Param('id') id: string) {
    return this.userService.findOne(parseInt(id, 10));
  }

  @Patch(':id')
  update(@Param('id') id: string, @Body() updateUserDto: UpdateUserDto) {
    return this.userService.update(parseInt(id, 10), updateUserDto);
  }

  @Delete(':id')
  remove(@Param('id') id: string) {
    return this.userService.remove(parseInt(id, 10));
  }
}